import { modelPicker } from "@/lib/model-picker";
import { auth } from "@/server/auth";
import { streamText } from "ai";
import { NextResponse } from "next/server";
// Use AI SDK types for proper type safety

interface SlidesRequest {
  title: string; // Generated presentation title
  prompt: string; // Original user prompt/request
  outline: string[]; // Array of main topics with markdown content
  language: string; // Language to use for the slides
  tone: string; // Style for image queries (optional)
  modelProvider?: string; // Model provider (openai, ollama, or lmstudio)
  modelId?: string; // Specific model ID for the provider
  searchResults?: Array&lt;{ query: string; results: unknown[] }&gt;; // Search results for context
}
// TODO: Add table and chart to the available layouts
const slidesTemplate = `
You are an expert presentation designer.Your task is to create an engaging presentation in XML format.
## CORE REQUIREMENTS

1. FORMAT: Use &lt;SECTION&gt; tags for each slide
2. CONTENT: DO NOT copy outline verbatim - expand with examples, data, and context
3. VARIETY: Each slide must use a DIFFERENT layout component
4. VISUALS: Include detailed image queries (10+ words) on every slide

## PRESENTATION DETAILS
- Title: {TITLE}
- User's Original Request: {PROMPT}
- Current Date: {CURRENT_DATE}
- Outline (for reference only): {OUTLINE_FORMATTED}
- Language: {LANGUAGE}
- Tone: {TONE}
- Total Slides: {TOTAL_SLIDES}

## RESEARCH CONTEXT
{SEARCH_RESULTS}

## PRESENTATION STRUCTURE
\`\`\`xml
&lt;PRESENTATION&gt;


&lt;SECTION layout="left" | "right" | "vertical"&gt;
  
  
&lt;/SECTION&gt;



&lt;/PRESENTATION&gt;
\`\`\`

## SECTION LAYOUTS
Vary the layout attribute in each SECTION tag to control image placement:
- layout="left" - Root image appears on the left side
- layout="right" - Root image appears on the right side
- layout="vertical" - Root image appears at the top

Use all three layouts throughout the presentation for visual variety.

## AVAILABLE LAYOUTS
Choose ONE different layout for each slide (use these exact XML tags so our parser recognizes them):

1. COLUMNS: For comparisons
\`\`\`xml
&lt;COLUMNS&gt;
  <div><h3>First Concept</h3><p>Description</p></div>
  <div><h3>Second Concept</h3><p>Description</p></div>
&lt;/COLUMNS&gt;
\`\`\`

2. BULLETS: For key points
\`\`\`xml
&lt;BULLETS&gt;
  <div><h3>Main Point 1 </h3><p>Description</p></div>
  <div><h3>Main Point 2 </h3><p>Second point with details</p></div>
&lt;/BULLETS&gt;
\`\`\`

3. ICONS: For concepts with symbols
\`\`\`xml
&lt;ICONS&gt;
  <div>&lt;ICON query="rocket" /&gt;<h3>Innovation</h3><p>Description</p></div>
  <div>&lt;ICON query="shield" /&gt;<h3>Security</h3><p>Description</p></div>
&lt;/ICONS&gt;
\`\`\`

4. CYCLE: For processes and workflows
\`\`\`xml
&lt;CYCLE&gt;
  <div><h3>Research</h3><p>Initial exploration phase</p></div>
  <div><h3>Design</h3><p>Solution creation phase</p></div>
  <div><h3>Implement</h3><p>Execution phase</p></div>
  <div><h3>Evaluate</h3><p>Assessment phase</p></div>
&lt;/CYCLE&gt;
\`\`\`

5. ARROWS: For cause-effect or flows
\`\`\`xml
&lt;ARROWS&gt;
  <div><h3>Challenge</h3><p>Current market problem</p></div>
  <div><h3>Solution</h3><p>Our innovative approach</p></div>
  <div><h3>Result</h3><p>Measurable outcomes</p></div>
&lt;/ARROWS&gt;
\`\`\`

5b. ARROW-VERTICAL: For vertical step-by-step flows (preferred for linear phases)
\`\`\`xml
&lt;ARROW-VERTICAL&gt;
  <div><h3>Discover</h3><p>Research & requirements.</p></div>
  <div><h3>Design</h3><p>UX & architecture.</p></div>
  <div><h3>Deliver</h3><p>Build, test, deploy.</p></div>
&lt;/ARROW-VERTICAL&gt;
\`\`\`

6. TIMELINE: For chronological progression
\`\`\`xml
&lt;TIMELINE&gt;
  <div><h3>2022</h3><p>Market research completed</p></div>
  <div><h3>2023</h3><p>Product development phase</p></div>
  <div><h3>2024</h3><p>Global market expansion</p></div>
&lt;/TIMELINE&gt;
\`\`\`

7. PYRAMID: For hierarchical importance
\`\`\`xml
&lt;PYRAMID&gt;
  <div><h3>Vision</h3><p>Our aspirational goal</p></div>
  <div><h3>Strategy</h3><p>Key approaches to achieve vision</p></div>
  <div><h3>Tactics</h3><p>Specific implementation steps</p></div>
&lt;/PYRAMID&gt;
\`\`\`

8. STAIRCASE: For progressive advancement
\`\`\`xml
&lt;STAIRCASE&gt;
  <div><h3>Basic</h3><p>Foundational capabilities</p></div>
  <div><h3>Advanced</h3><p>Enhanced features and benefits</p></div>
  <div><h3>Expert</h3><p>Premium capabilities and results</p></div>
&lt;/STAIRCASE&gt;
\`\`\`


9. IMAGES: Most slides needs at least one
\`\`\`xml

<img />
<img />
<img />


\`\`\`

10. BOXES: For simple information tiles
\`\`\`xml
&lt;BOXES&gt;
  <div><h3>Speed</h3> <p>Faster delivery cycles.</p></div>
  <div><h3>Quality</h3> <p>Automated testing & reviews.</p></div>
  <div><h3>Security</h3> <p>Shift-left security practices.</p></div>
&lt;/BOXES&gt;
\`\`\`

11. COMPARE: For side-by-side comparison
\`\`\`xml
&lt;COMPARE&gt;
  <div><h3>Solution A</h3> <li>Features 1</li> <li>Features 2</li></div>
  <div><h3>Solution B</h3> <li>Features 3</li> <li>Features 4</li></div>
&lt;/COMPARE&gt;
\`\`\`

12. BEFORE-AFTER: For transformation snapshots
\`\`\`xml
&lt;BEFORE-AFTER&gt;
  <div><h3>Before</h3> <p>Manual processes, scattered data.</p></div>
  <div><h3>After</h3> <p>Automated workflows, unified insights.</p></div>
&lt;/BEFORE-AFTER&gt;
\`\`\`

13. PROS-CONS: For trade-offs
\`\`\`xml
&lt;PROS-CONS&gt;
  &lt;PROS&gt;<h3>Pros</h3> <li>Pros 1</li> <li>Pros 2</li>  &lt;/PROS&gt;
  &lt;CONS&gt;<h3>Cons</h3> <li>Cons 1</li> <li>Cons 2</li>&lt;/CONS&gt;
&lt;/PROS-CONS&gt;
\`\`\`

14. TABLE: For tabular data. Preferred over other layouts for tabular data. It can also be used to do comparisons.
\`\`\`xml
<table>
  <tr><th>Header 1</th><th>Header 2</th></tr>
  <tr><td>Data 1</td><td>Data 2</td></tr>
</table>
\`\`\`

15. CHARTS: Use compact DATA rows (no TABLEs). The AI must emit \`&lt;DATA&gt;\` items inside \`&lt;CHART&gt;\`.
\`\`\`xml

&lt;CHART charttype="bar|pie|line|area|radar"&gt;
  &lt;DATA&gt;&lt;LABEL&gt;Q1&lt;/LABEL&gt;&lt;VALUE&gt;24&lt;/VALUE&gt;&lt;/DATA&gt;
  &lt;DATA&gt;&lt;LABEL&gt;Q2&lt;/LABEL&gt;&lt;VALUE&gt;36&lt;/VALUE&gt;&lt;/DATA&gt;
&lt;/CHART&gt;


&lt;CHART charttype="scatter"&gt;
  &lt;DATA&gt;&lt;X&gt;1&lt;/X&gt;&lt;Y&gt;2&lt;/Y&gt;&lt;/DATA&gt;
  &lt;DATA&gt;&lt;X&gt;3&lt;/X&gt;&lt;Y&gt;5&lt;/Y&gt;&lt;/DATA&gt;
&lt;/CHART&gt;
\`\`\`


## CONTENT EXPANSION STRATEGY
For each outline point:
- Add supporting data/statistics
- Include real-world examples
- Reference industry trends
- Add thought-provoking questions

## CRITICAL RULES
1. Generate exactly {TOTAL_SLIDES} slides. NOT MORE NOT LESS ! EXACTLY {TOTAL_SLIDES}
2. NEVER repeat layouts in consecutive slides
3. DO NOT copy outline verbatim - expand and enhance
4. Include at least one detailed image query in most of the slides
5. Use appropriate heading hierarchy
6. Vary the SECTION layout attribute (left/right/vertical) throughout the presentation
   - Use each layout (left, right, vertical) at least twice
   - Don't use the same layout more than twice in a row

7. Use only the XML tags shown above. Do not invent new tags or attributes.

Now create a complete XML presentation with {TOTAL_SLIDES} slides that significantly expands on the outline.
`;

export async function POST(req: Request) {
  try {
    const session = await auth();
    if (!session) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const {
      title,
      prompt: userPrompt,
      outline,
      language,
      tone,
      modelProvider = "openai",
      modelId,
      searchResults,
    } = (await req.json()) as SlidesRequest;

    if (!title || !outline || !Array.isArray(outline) || !language) {
      return NextResponse.json(
        { error: "Missing required fields" },
        { status: 400 },
      );
    }

    // Format search results
    let searchResultsText = "No research data available.";
    if (searchResults && searchResults.length &gt; 0) {
      const searchData = searchResults
        .map((searchItem, index: number) =&gt; {
          const query = searchItem.query || `Search ${index + 1}`;
          const results = Array.isArray(searchItem.results)
            ? searchItem.results
            : [];

          if (results.length === 0) return "";

          const formattedResults = results
            .map((result: unknown) =&gt; {
              const resultObj = result as Record&lt;string, unknown&gt;;
              return `- ${resultObj.title || "No title"}\n  ${resultObj.content || "No content"}\n  ${resultObj.url || "No URL"}`;
            })
            .join("\n");

          return `**Search Query ${index + 1}:** ${query}\n**Results:**\n${formattedResults}\n---`;
        })
        .filter(Boolean)
        .join("\n\n");

      if (searchData) {
        searchResultsText = `The following research was conducted during outline generation:\n\n${searchData}`;
      }
    }

    const currentDate = new Date().toLocaleDateString("en-US", {
      weekday: "long",
      year: "numeric",
      month: "long",
      day: "numeric",
    });

    const model = modelPicker(modelProvider, modelId);

    // Format the prompt with template variables
    const formattedPrompt = slidesTemplate
      .replace(/{TITLE}/g, title)
      .replace(/{PROMPT}/g, userPrompt || "No specific prompt provided")
      .replace(/{CURRENT_DATE}/g, currentDate)
      .replace(/{LANGUAGE}/g, language)
      .replace(/{TONE}/g, tone)
      .replace(/{OUTLINE_FORMATTED}/g, outline.join("\n\n"))
      .replace(/{TOTAL_SLIDES}/g, outline.length.toString())
      .replace(/{SEARCH_RESULTS}/g, searchResultsText);

    const result = streamText({
      model,
      prompt: formattedPrompt,
    });

    return result.toDataStreamResponse();
  } catch (error) {
    console.error("Error in presentation generation:", error);
    return NextResponse.json(
      { error: "Failed to generate presentation slides" },
      { status: 500 },
    );
  }
}
